import cloudbase from '../utils/cloudbase';

/**
 * 用户服务
 */
const userService = {
  /**
   * 匿名登录
   * @returns {Promise<Object>} 登录结果
   */
  async anonymousLogin() {
    try {
      return await cloudbase.anonymousLogin();
    } catch (error) {
      console.error('匿名登录失败:', error);
      throw error;
    }
  },
  
  /**
   * 邮箱登录
   * @param {String} email 邮箱
   * @param {String} password 密码
   * @returns {Promise<Object>} 登录结果
   */
  async emailLogin(email, password) {
    try {
      const auth = cloudbase.getAuth();
      return await auth.signInWithEmailAndPassword(email, password);
    } catch (error) {
      console.error('邮箱登录失败:', error);
      throw error;
    }
  },
  
  /**
   * 邮箱注册
   * @param {String} email 邮箱
   * @param {String} password 密码
   * @returns {Promise<Object>} 注册结果
   */
  async emailRegister(email, password) {
    try {
      const auth = cloudbase.getAuth();
      return await auth.signUpWithEmailAndPassword(email, password);
    } catch (error) {
      console.error('邮箱注册失败:', error);
      throw error;
    }
  },
  
  /**
   * 退出登录
   * @returns {Promise<Object>} 退出结果
   */
  async logout() {
    try {
      const auth = cloudbase.getAuth();
      return await auth.signOut();
    } catch (error) {
      console.error('退出登录失败:', error);
      throw error;
    }
  },
  /**
   * 获取当前用户ID
   * @returns {Promise<String>} 用户ID
   */
  async getCurrentUserId() {
    try {
      // 优先从本地存储获取用户ID
      const storedUserId = localStorage.getItem('monopoly_user_id');
      if (storedUserId) {
        console.log('从本地存储获取到用户ID:', storedUserId);
        return storedUserId;
      }
      
      // 检查登录状态
      const isLoggedIn = await cloudbase.checkLoginStatus();
      console.log('检查登录状态:', isLoggedIn);
      
      // 如果未登录，尝试匿名登录
      if (!isLoggedIn) {
        console.log('未登录，尝试匿名登录');
        await cloudbase.anonymousLogin();
      }
      
      // 获取用户ID
      const userId = await cloudbase.getUserId();
      console.log('获取到用户ID:', userId);
      
      // 保存到本地存储
      if (userId) {
        localStorage.setItem('monopoly_user_id', userId);
      }
      
      return userId;
    } catch (error) {
      console.error('获取当前用户ID失败:', error);
      return null;
    }
  },

  /**
   * 获取当前用户
   * @returns {Promise<Object>} 用户信息
   */
  async getCurrentUser() {
    try {
      const auth = cloudbase.getAuth();
      const loginState = await auth.getLoginState();
      
      if (!loginState) {
        return null;
      }
      
      return loginState.user;
    } catch (error) {
      console.error('获取当前用户信息失败:', error);
      return null;
    }
  }
};

export default userService;